package com.conqueror.languagechangedemo;

import android.content.Intent;
import android.content.res.Configuration;
import android.content.res.Resources;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.util.DisplayMetrics;
import android.util.Log;
import android.widget.TextView;

import java.util.Locale;

public class MainActivity extends AppCompatActivity {

    private TextView tv;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        tv = (TextView) findViewById(R.id.tv);

    }

    protected void showLanguage(String language) {
        //设置应用语言类型
        Resources resources = getResources();
        Configuration config = resources.getConfiguration();
        DisplayMetrics dm = resources.getDisplayMetrics();

        if (language.equals("CN")) {
            config.locale = Locale.SIMPLIFIED_CHINESE;
        } else if (language.contains("TW")) {
            config.locale = Locale.TRADITIONAL_CHINESE;
        } else {
            config.locale = Locale.ENGLISH;
        }
        resources.updateConfiguration(config, dm);

        tv.setText(R.string.tv_name);
//        //保存设置语言的类型（这个里面我先保存一下，下面会讲到他的用处）
//        PreferenceUtil.commitString("language", language);
    }

    @Override
    protected void onResume() {
        super.onResume();
//        String LAN = PreferenceUtil.getString("language","");
        Locale locale = Locale.getDefault();
        String language = locale.getLanguage();
        String country = locale.getCountry();
        String displayLanguage = locale.getDisplayLanguage();
        String displayCountry = locale.getDisplayCountry();
        Log.i("语言————————", language);
        Log.e("displayLanguage", "----------" + displayLanguage);
        Log.e("country", "----------" + country + "----------------displayCountry-------" + displayCountry);
//        if(!language.equals("")){
//            if(!LAN.equals(language)){
//                freshView();//重新启动MainActivity
//
//            }
//        }
        showLanguage(country);
    }


    private void freshView() {
        Intent intent = new Intent(this, MainActivity.class);
        intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
        startActivity(intent);
    }
}
